import { Message } from 'element-ui'
import * as XLSX from "xlsx"
import request from '@/utils/request'


/**
 * 上传前对文件进行判断
 * @param {*} file 上传的文件
 * @returns 
 */
export const E_beforeUpload = function(file) {
    const type = file.name.slice(file.name.length - 4, file.name.length)
    const isXlsx = type === "xlsx";
    //除以两次1024是将MB转成字节
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isLt100M) {
        Message({
            message: `${file.name}文件过大,要小于100MB`,
            type: "error",
        });
        return false;
    }
    if (isXlsx) {
        return true;
    } else {
        Message({
            message: ` ${file.name}文件格式不正确, 请选择xlsx文件`,
            type: "error",
        });
        return false;
    }
}

/**
 * 上传成功消息提示
 * @param {*} result 上传成功返回的参数
 */
export const E_uploadSuccess = function(result) {
    if (result.code === 1) {
        Message({ type: 'success', message: result.data })
    } else {
        Message({ type: 'error', message: result.msg })
    }
}


/**
 * 导出excel
 * @param {*} data 下载的数据来源
 * @param {*} fileName 下载好的文件名(xls)结尾
 * @returns 
 */
export const E_downloadExcel = async function(data) {
    let res = await request({
        method: 'post',
        url: '/UserManage/DownLoadExcelIds',
        data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
        }
    });
    return res
}

export const dataHandler =function(data,tableColumns){
    const newData = data.map(obj => {
        const newObj = {};
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const column = tableColumns.find(c => c.prop === key);
            newObj[column.label] = obj[key];
          }
        }
        return newObj;
      });
    return newData
}

export const downloadExcel= function(data,fileName){
    /* 新建一个 workbook */
    // console.log(this.list)
    fileName = fileName || "下载表格.xlsx"
    const wb = XLSX.utils.book_new();

    /* 将数据转换为 worksheet */
    const ws = XLSX.utils.json_to_sheet(data);

    /* 将 worksheet 添加到 workbook 中 */
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    /* 导出文件并保存到本地 */
    XLSX.writeFile(wb, fileName);
}
